<template>
  <div>
    <div class="card" style="margin-bottom: 8px">
      <el-input style="width: 240px" v-model="data.name" placeholder="请输入名称查询" prefix-icon="Search" />
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 8px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="deleteBatch">批量删除</el-button>
      <!--      <el-button type="primary">导入</el-button>-->
      <!--      <el-button type="primary">导出</el-button>-->
    </div>

    <div class="card" style="margin-bottom: 8px">
      <el-table :data="data.tableData"  @selection-change="handleSelectionChange" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column  label="账号" prop="username" />
        <el-table-column  label="姓名" prop="name" />
        <el-table-column  label="角色" prop="role" />
        <el-table-column  label="头像" >
          <template #default="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" style="display: block; width: 40px; height: 40px; border-radius: 50%">
          </template>
        </el-table-column>
        <el-table-column  label="性别" prop="sex" />
        <el-table-column  label="工号" prop="no" />
        <el-table-column  label="年龄" prop="age" />
        <el-table-column  label="个人介绍" prop="description" />
        <el-table-column  label="部门" prop="departmentName" />

        <el-table-column label="操作">
          <!--   link---将按钮样式设置为文本链接，继承父元素的颜色，并移除默认的按钮背景和边框。      -->
          <template #default="scope">
            <el-button type="primary" size="small" :icon="Edit" link @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" size="small" :icon="Delete" link @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!--    不写这个无法完成点击分页效果 @current-change="load"  -->
      <div class="card" style="margin-bottom: 8px">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <!--  新增---弹框  -->
    <el-dialog v-model="data.formVisible" title="员工信息" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" style="padding-right: 40px; padding-top: 20px" label-width="80px">
<!--  :disabled="data.form.id" 禁用data.form.id的值 -->
        <el-form-item label="账号" prop="username">
          <el-input :disabled="data.form.id" v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
<!-- list-type="picture" 显示上传图片的样子 -->
        <el-form-item label="头像" prop="username">
          <el-upload
              :action = uploadUrl
              list-type="picture"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称"/>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="data.form.sex">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="工号" prop="on">
          <el-input v-model="data.form.no" autocomplete="off" placeholder="请输入工号"/>
        </el-form-item>

        <el-form-item label="年龄">
          <el-input-number style="width: 180px;" :min="18" v-model="data.form.age" autocomplete="off" placeholder="请输入年龄"/>
        </el-form-item>

        <el-form-item label="个人介绍">
          <el-input :rows="3" type="textarea" v-model="data.form.description" autocomplete="off" placeholder="请输入个人介绍"/>
        </el-form-item>


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>


<script setup>
import {reactive, ref} from "vue";
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {
    // 初始化时账号为空
  },
  ids:{},
  rules: {
      username:[
        { required: true, message: '请输入账号', trigger: 'blur'}
      ],
      name:[
      { required: true, message: '请输入名称', trigger: 'blur'}
      ],
      on:[
      { required: true, message: '请输入工号', trigger: 'blur'}
      ]
  }
});

const formRef = ref()


// 分页查询---加载数据
const load = () =>{
  request.get('/employee/selectPage',{
    params:{
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name:data.name
    }
  }).then(res =>{
    data.tableData = res.data.list
    data.total = res.data.total
  })
}

// 页面初始化加载数据
load()

//  重置按钮
const reset = () =>{
  data.name = null
  load()
}

const uploadUrl = "http://localhost:9090/files/upload";
const handleAvatarSuccess = (res) =>{
  console.log(res.data)
  data.form.avatar = res.data
}

// 新增按钮
const handleAdd = () =>{
  data.formVisible = true
  data.form = {}  //清除数据
}


  // 判断是新增还是修改
  const save = () =>{   //在一个方法里面做两种操作，一个新增，一个修改
    // formRef.value.validate((valid) =>{
    //   if (valid){
    //     data.form.id ? update() : add()
    //   }
    // })
    data.form.id ? update() : add()
  }

  // 新增按钮
  const add = () =>{
    request.post("/employee/add",data.form).then(res =>{  //新增没有id
      if(res.code === 200){
        data.formVisible = false //关闭弹窗
        ElMessage.success("操作成功")
        load()  //新增成功之后重新加载数据
      }else{
        ElMessage.error("操作失败")
      }
    })
  }

  // 修改按钮
  const update = () =>{
    request.post("/employee/update",data.form).then(res =>{    //修改有id
      if(res.code === 200){
        data.formVisible = false //关闭弹窗
        ElMessage.success("操作成功")
        load()  //修改成功之后重新加载数据
      }else{
        ElMessage.error("操作失败")
      }
    })
  }

  // 修改按钮
  const handleUpdate = (row) =>{
    data.form = JSON.parse(JSON.stringify(row))    //深拷贝一个对象 用于编辑 这样就不会影响行对象的数据
    data.formVisible = true
  }

  // 删除---单个删除
  const del = (id) =>{
    ElMessageBox.confirm('删除数据之后无法恢复，确认继续吗？','删除确认',{type:'warning'}).then(()=>{
      request.delete("/employee/deleteById/" +id).then(res =>{
        if(res.code === 200){
          ElMessage.success("操作成功")
          load()  //删除成功之后重新加载数据
        }else{
          ElMessage.error("操作失败")
        }
      })
    }).catch()
  }

  const handleSelectionChange = (rows) => {    //返回所以选中的行对象数组
    // console.log(rows)

  //   从选中的行数组里面取出所有行的id组成一个新的数组
    data.ids = rows.map(row => row.id)
    console.log(data.ids)
  }

  // 批量删除
  const deleteBatch = () => {
    if (data.ids.length === 0){
      ElMessage.success("请选择数据")
    }
    ElMessageBox.confirm('删除数据之后无法恢复，确认继续吗？','删除确认',{type:'warning'}).then(()=>{

      request.delete("/employee/deleteBatch", { data: data.ids }).then(res =>{
        if(res.code === 200){
          ElMessage.success("操作成功")
          load()  //删除成功之后重新加载数据
        }else{
          ElMessage.error("操作失败,请选择数据")
        }
      })

    }).catch()
  }

</script>


<style scoped>

</style>